﻿using System;
using System.Collections.Generic;
using System.Text;
using StarBotDotNet;

namespace StarBotDotNet
{

    public class UnitDictionary : SortedDictionary<UnitType, SortedDictionary<int, UnitData>>
    {
        Dictionary<UnitData, UnitParty> unitToParties = new Dictionary<UnitData, UnitParty>();


        public UnitParty GetParty(UnitData unit)
        {
            return unitToParties[unit];
        }

        public UnitParty SetParty(UnitData unit, UnitParty party)
        {
            return unitToParties[unit] = party;
        }

        public UnitData GetUnitByIdOnly(int id)
        {
            foreach (UnitType type in this.Keys)
            {
                if (this[type].ContainsKey(id))
                {
                    return this[type][id];
                }
            }
            return null;
        }

        public IEnumerable<UnitData> GetAllUnits()
        {
        
            foreach (UnitType type in this.Keys)
            {
                foreach (UnitData un in this[type].Values)
                {
                    yield return un;
                }
            }
        }

        public delegate void UnitProcessor(UnitData unit);

        public void ForEach(UnitProcessor processor)
        {

            foreach (UnitData un in GetAllUnits())
            {
                processor(un);
            }
            
        }

        public bool ContainsUnit(UnitType unitType, int p)
        {
            if (!this.ContainsKey(unitType))
            {
                return false;
            }

            if (!this[unitType].ContainsKey(p))
            {
                return false;
            }

            return true;
        }


        internal void Add(UnitData unit, UnitParty party)
        {
            if (!this.ContainsKey(unit.Type))
            {
                this.Add(unit.Type, new SortedDictionary<int, UnitData>());
            }
            unitToParties.Add(unit, party);
            this[unit.Type].Add(unit.ID, unit);
        }

        

        internal void Remove(UnitData unit)
        {
            if (unit != null)
            {
                this[unit.Type].Remove(unit.ID);
                unitToParties.Remove(unit);
                if (this[unit.Type].Count <= 0)
                {
                    this.Remove(unit.Type);
                }
            }
            else
            {
                Utilities.WriteColorLine(ConsoleColor.Red, "WARNING: UnitDictionary.Remove was passed a null UnitData");
            }
        }

        internal bool NotAssigned(UnitData unit)
        {
            return GetParty(unit) == null;
        }
    }

}
